<!--
 @description 板木主页
 @fileName index.vue
 @author maliang
 @created 2022/03/05 13:40:00
-->
<template>
  <div>
    <div class="top-container">
      <div class="banner">
        <img src="@/assets/image/banner-produces.png">
      </div>
      <div class="main-core-page">
        <span class="icon-tip left" />
        <span class="icon-tip right" />
        <div class="wrapper">
          <div class="main-title">
            <div style="flex:1">核心指标</div>
            <div class="core-time" @click="showCalendar = true">
              <span>{{ coreDateShow }}</span>
              <svg-icon icon-class="xia" />
            </div>
          </div>
          <core-data :core-date="coreDate" />
        </div>
      </div>
    </div>
    <div id="tabFixed" class="tab-titles" :class="{ is_fixed: isFixed }">
      <div class="tab-box" :class="{ 'has-sub': tabName !== 'order' }">
        <template v-for="(item, index) in pageTabs">
          <div
            :key="index"
            class="tab "
            :class="{ active: tabName === item.name }"
            @click="tabName = item.name"
          >
            <span>{{ item.title }}</span>
          </div>
        </template>
      </div>
    </div>
    <div class="main-page">
      <module-item
        class="module-item"
        :module-title="tabName + '本部近6月产量'"
        :describe-info="{
          fileName: 'plankWood',
          moudleName: '6month',
        }"
      >
        <span
          slot="other"
          class="this-year-num"
        >本年总产量:<i>{{
          yearCompletedQuantity | filterForamtThousand
        }}</i>{{ unitName }}</span>
        <line-chart
          slot="content"
          :show-legend="true"
          :x-axis-data="sofaOutputSixXAxisData"
          :series-data="sofaOutputSixSeriesData"
        />
      </module-item>
      <module-item
        class="module-item"
        :module-title="tabName + '本部近30日产量'"
        :describe-info="{
          fileName: 'plankWood',
          moudleName: '30day',
        }"
      >
        <line-chart
          slot="content"
          :show-legend="false"
          :x-axis-data="thirtyDayXAxisData"
          :series-data="thirtyDaySixSeriesData"
          :axis-label-rotate="40"
          :symbol-size="4"
          :grid-data="{ top: 20 }"
          @selectedCallback="selectedCallback"
        />
      </module-item>
      <module-item
        class="module-item"
        :module-title="tabName + '各分厂产量'"
        :describe-info="{
          fileName: 'plankWood',
          moudleName: 'production',
        }"
      >
        <div slot="other">
          <span class="date-box">{{ columnarDate }}</span>
        </div>
        <histogram
          slot="content"
          :show-legend="false"
          :x-axis-data="yieldColumnarXAxisData"
          :series-data="yieldColumnarSeriesData"
          :series-bar-config="seriesBarConfig"
          @selectedCallback="columnarSelectedCallback"
        />
      </module-item>
      <module-item class="module-item" :module-title="currenName">
        <div slot="other">
          <span class="date-box">{{ columnarDate }}</span>
        </div>
        <pieChart slot="content" :series-data="pieSeriesData" />
      </module-item>
    </div>
    <van-calendar
      v-model="showCalendar"
      class="custom-calendar"
      color="#12B9A3"
      :row-height="40"
      :min-date="calendarMinDate"
      :max-date="calendarMaxDate"
      @confirm="onConfirmCalendar"
    />
  </div>
</template>
<script>
import CoreData from './components/CoreData'
import CoreDateMixin from '@/mixins/CoreDate'
import ScrollTab from '@/mixins/ScrollTab'
import ModuleItem from '@/views/delivery/components/ModuleItem'
import LineChart from '@/views/delivery/components/LineChart'
import Histogram from '@/views/delivery/components/Histogram'
import PieChart from '@/views/software/components/PieChart'
import {
  getSixMonthTrend,
  getThirtyDayTrend,
  getFactoryQuantity,
  getFactorySubclassQuantity,
  getThisYearBigTypeQuantity
} from '@/apis/plankWood'
export default {
  name: 'PlankWood',
  components: { CoreData, ModuleItem, LineChart, Histogram, PieChart },
  mixins: [CoreDateMixin, ScrollTab],
  data() {
    return {
      showCalendar: false,
      tabName: '板式',
      pageTabs: [
        { name: '板式', title: '板式' },
        { name: '实木', title: '实木' }
      ],
      yearCompletedQuantity: '-',

      sofaOutputSixXAxisData: null,
      sofaOutputSixSeriesData: [
        { name: '今年', field: 'completedQuantity' },
        { name: '去年', field: 'lastyearQuantity' }
      ],
      thirtyDayXAxisData: null,
      thirtyDaySixSeriesData: [{ name: '产量', field: 'quantity' }],
      yieldColumnarXAxisData: null,
      yieldColumnarSeriesData: [
        {
          name: '产量',
          field: 'quantity'
        }
      ],
      pieSeriesData: null,
      typeOptions: [
        {
          name: '分厂'
        },
        {
          name: '小类'
        }
      ],
      currenType: '分厂',
      currenName: null,
      columnarDate: null,
      seriesBarConfig: {
        barWidth: '20px'
      } // 自定义柱状图配置
    }
  },
  computed: {
    unitName() {
      if (this.tabName === '床垫') {
        return '张'
      }
      if (this.tabName === '小件') {
        return '件'
      }
      return '套'
    }
  },
  watch: {
    coreDate: {
      handler(val) {
        this.columnarDate = val
        this.getCurrentPageAllChartsData()
        this.findSofaColumnar()
      },
      immediate: true
    },
    tabName: {
      handler() {
        this.getCurrentPageAllChartsData()
        this.findSofaColumnar()
      }
    }
  },
  methods: {
    // 获取所有图表数据
    async getCurrentPageAllChartsData() {
      this.sofaOutputSixXAxisData = null
      this.thirtyDayXAxisData = null
      this.yearCompletedQuantity = '-'
      const findSixMonthTrend = getSixMonthTrend({
        factoryType: this.tabName
      }) // 近6月趋势
      const findThirtyDayTrend = getThirtyDayTrend({
        factoryType: this.tabName,
        date: this.coreDate
      }) // 近30日趋势
      const findThisYearData = getThisYearBigTypeQuantity({
        // date: this.coreDate,
        factoryType: this.tabName
      }) // 本年总产量
      try {
        const [
          sixMonthTrendRes,
          thirtyDayTrendRes,
          thisYearRes
        ] = await Promise.all([
          findSixMonthTrend,
          findThirtyDayTrend,
          findThisYearData
        ])
        // 近6月趋势数据模拟
        // sixMonthTrendRes.data = [
        //     {
        //         completedQuantity: 3,
        //         date: "2021-06",
        //         factoryType: "今年",
        //     },
        //     {
        //         completedQuantity: 8,
        //         date: "2021-07",
        //         factoryType: "今年",
        //     },
        //     {
        //         completedQuantity: 10,
        //         date: "2020-06",
        //         factoryType: "去年",
        //     },
        //     {
        //         completedQuantity: 2,
        //         date: "2021-05",
        //         factoryType: "今年",
        //     },
        //     {
        //         completedQuantity: 11,
        //         date: "2020-07",
        //         factoryType: "去年",
        //     },
        //     {
        //         completedQuantity: 3,
        //         date: "2020-05",
        //         factoryType: "去年",
        //     },
        // ];
        if (sixMonthTrendRes.data) {
          let thisYearData = sixMonthTrendRes.data.filter(
            (item) => item.factoryType === '今年'
          )
          let lastYearData = sixMonthTrendRes.data.filter(
            (item) => item.factoryType === '去年'
          )
          thisYearData = thisYearData.sort((a, b) => {
            return (
              Number(a.date.replace(/-/g, '')) -
                            Number(b.date.replace(/-/g, ''))
            )
          })
          lastYearData = lastYearData.sort((a, b) => {
            return (
              Number(a.date.replace(/-/g, '')) -
                            Number(b.date.replace(/-/g, ''))
            )
          })
          thisYearData.forEach((item) => {
            item.date = item.date.substring(5, 7)
          })
          lastYearData.forEach((item) => {
            item.date = item.date.substring(5, 7)
          })

          const newSixMonthTrend = []
          thisYearData.forEach((item) => {
            const data = lastYearData.find(
              (row) => row.date === item.date
            )
            newSixMonthTrend.push({
              date: item.date,
              completedQuantity: item.quantity,
              lastyearQuantity: data.quantity
            })
          })
          const { xAxisData, seriesData } = this.resetLineChartData(
            newSixMonthTrend,
            this.sofaOutputSixSeriesData,
            'date',
            '月',
            false
          )
          this.sofaOutputSixXAxisData = xAxisData
          this.sofaOutputSixSeriesData = seriesData
        }
        // // 近30日趋势数据模拟
        // thirtyDayTrendRes.data = [
        //     {
        //         quantity: 4,
        //         date: "2021-12-09",
        //     },
        //     {
        //         quantity: 6,
        //         date: "2021-12-03",
        //     },
        //     {
        //         quantity: 8,
        //         date: "2021-12-05",
        //     },
        // ];
        if (thirtyDayTrendRes.data) {
          // thirtyDayTrendRes.data.forEach((item) => {
          //     item.date = item.date
          //         .substring(5, item.date.length)
          //         .replace(/-/, ".");
          // });
          const { xAxisData, seriesData } = this.resetLineChartData(
            thirtyDayTrendRes.data,
            this.thirtyDaySixSeriesData,
            'date'
          )
          this.thirtyDayXAxisData = xAxisData
          this.thirtyDaySixSeriesData = seriesData
        }
        this.yearCompletedQuantity = thisYearRes.data
      } catch (error) {
        this.$toast.fail('系统异常')
      }
    },
    // 根据日期查询分厂数据
    async findSofaColumnar() {
      this.currenName = '暂无数据'
      this.pieSeriesData = null
      this.yieldColumnarXAxisData = null
      const findSofaColumnar = getFactoryQuantity({
        date: this.columnarDate,
        factoryType: this.tabName
      })
      try {
        const [sofaColumnarRes] = await Promise.all([findSofaColumnar])
        // 软体看板分厂/小类
        // sofaColumnarRes.data = [
        //     {
        //         completedQuantity: 4,
        //         factoryName: "沙发五厂",
        //         subclass: "沙发",
        //     },
        //     {
        //         completedQuantity: 6,
        //         factoryName: "沙发七场",
        //         subclass: "功能单椅",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂",
        //         subclass: "软包",
        //     },
        // ];
        if (sofaColumnarRes.data) {
          const { xAxisData, seriesData } = this.resetLineChartData(
            sofaColumnarRes.data,
            this.yieldColumnarSeriesData,
            'factoryName'
          )
          this.yieldColumnarXAxisData = xAxisData
          this.yieldColumnarSeriesData = seriesData
          if (this.yieldColumnarXAxisData[0]) {
            this.findPieCharts(this.yieldColumnarXAxisData[0])
          } else {
            this.currenName = '暂无数据'
            this.pieSeriesData = []
          }
        }
      } catch (error) {
        this.$toast.fail('系统异常')
      }
    },
    // 根据工厂看小类或者根据小类看工厂
    async findPieCharts(name) {
      this.pieSeriesData = null
      this.currenName = name
      const findSofaPie = getFactorySubclassQuantity({
        date: this.columnarDate,
        factoryName: name
        //   type: this.tabName,
      })
      try {
        const [sofaPieRes] = await Promise.all([findSofaPie])
        // 软体看板分厂/小类
        // sofaPieRes.data = [
        //     {
        //         completedQuantity: 4,
        //         factoryName: "沙发五厂",
        //         subclass: "沙发",
        //     },
        //     {
        //         completedQuantity: 6,
        //         factoryName: "沙发七场",
        //         subclass: "功能单椅",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂",
        //         subclass: "软包",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂1",
        //         subclass: "软包1",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂2",
        //         subclass: "软包2",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂3",
        //         subclass: "软包3",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂4",
        //         subclass: "软包4",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂5",
        //         subclass: "软包5",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂6",
        //         subclass: "软包6",
        //     },
        //     {
        //         completedQuantity: 8,
        //         factoryName: "绷皮厂7",
        //         subclass: "软包7",
        //     },
        // ];
        if (sofaPieRes.data) {
          this.pieSeriesData = this.pieChartsDataReset(
            sofaPieRes.data,
            'quantity',
            'smallType'
          )
        }
      } catch (error) {
        this.$toast.fail('系统异常')
      }
    },
    // 饼图数据处理
    pieChartsDataReset(list, valueField, nameField) {
      const newList = []
      list.forEach((item) => {
        const obj = {
          value: item[valueField],
          name: item[nameField]
        }
        newList.push(obj)
      })
      return newList
    },
    // 折线图数据处理(list: 未处理前的图表数据；seriesData：图列名称与对应字段；xAxisField：x轴对应字段  )
    resetLineChartData(
      list,
      seriesData,
      xAxisField,
      unit = '',
      isSort = true
    ) {
      seriesData.forEach((item) => {
        item.data = []
      })
      let copyLsit = JSON.parse(JSON.stringify(list))
      const copySeriesData = JSON.parse(JSON.stringify(seriesData))
      const xAxisData = []
      if (xAxisField === 'date' && isSort) {
        // 根据日期排序
        copyLsit = copyLsit.sort((a, b) => {
          return (
            Number(a.date.replace(/-/g, '')) -
                        Number(b.date.replace(/-/g, ''))
          )
        })
      }
      copyLsit.forEach((item) => {
        xAxisData.push(item[xAxisField] + unit)
        copySeriesData.forEach((row) => {
          row.data.push(item[row.field])
        })
      })
      return {
        xAxisData,
        seriesData: copySeriesData
      }
    },
    changeTypeHandle(item) {
      this.currenType = item.name
      this.findSofaColumnar()
    },
    selectedCallback(index) {
      this.columnarDate = this.thirtyDayXAxisData[index]
      this.findSofaColumnar()
    },
    columnarSelectedCallback(index) {
      const name = this.yieldColumnarXAxisData[index]
      this.findPieCharts(name)
    }
  }
}
</script>
<style lang="less" scoped>
// 解决部分机型第一次打开日历选择弹框后出现空白的问题
/deep/.van-calendar__popup.van-popup--bottom,
.van-calendar__popup.van-popup--top {
    height: 79.9%;
}
.banner {
    margin-top: -3px;
}
.tab-box {
    border-radius: 6px !important;
}
.module-item {
    margin-top: 10px;
    position: relative;
    .this-year-num {
        position: absolute;
        right: 10px;
        top: 18px;
        z-index: 2;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 16px;
        letter-spacing: 1px;
        > i {
            font-style: normal;
            color: #e8684a;
            letter-spacing: 0;
        }
    }
    .type-btn {
        display: flex;
        span {
            width: 44px;
            height: 24px;
            border: 1px solid #eeeeee;
            background-color: #eeeeee;
            text-align: center;
            line-height: 22px;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.4);
            &:nth-child(1) {
                border-radius: 4px 0 0 4px;
            }
            &:nth-child(2) {
                border-radius: 0 4px 4px 0;
            }
        }
        .active {
            background: #12b9a3;
            box-shadow: 0px 2px 4px 0px rgba(18, 185, 163, 0.3);
            color: #fff;
            border: 1px solid #12b9a3;
        }
    }
    .date-box {
        position: absolute;
        right: 10px;
        top: 18px;
        z-index: 2;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 16px;
        letter-spacing: 1px;
    }
}
</style>
